package com.lnsf.bookstore.common.exception;

import com.lnsf.bookstore.common.dto.ResultFailDto;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * 异常处理器
 *
 * @author hhy
 * @date 2018年2月23日 下午10:16:19
 * @controllerAdvice最为实用的一个场景就是将所有@ExceptionHandler方法收集到一个类中，这样所有的异常都能在一个地方进行一致处理。
 */
@ControllerAdvice(value = {"com.lnsf.bookstore"})
public class RRExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 自定义异常
     */
    @ExceptionHandler(RException.class)
    @ResponseBody
    public Object handleRRException(RException e) {
        return new ResultFailDto(Integer.toString(e.getCode()),e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(DuplicateKeyException.class)
    public Object handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        return new ResultFailDto("数据库中已存在该记录");
    }

    @ExceptionHandler(AuthorizationException.class)
    public Object handleAuthorizationException(AuthorizationException e) {
        logger.error(e.getMessage(), e);
        //return new ResultFailDto("没有权限，请联系管理员授权");
        return "500";
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return new ResultFailDto(e.getMessage());
    }

    @ExceptionHandler(ApiRRException.class)
    @ResponseBody
    public Object handleApiRRException(ApiRRException e) {
        HashMap result = new HashMap();
        result.put("errno", e.getErrno());
        result.put("errmsg", e.getErrmsg());
        return result;
    }
}
